import 'package:dailoz/dio/http_util.dart';
import 'package:dailoz/response_json_entity.dart';
import 'package:dailoz/utils/TaskUtils.dart';
import 'package:dailoz/utils/map_sort.dart';
import 'package:dailoz/widgets/add_task.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TaskPageService {
  static Future<Map<String, dynamic>> getTaskByTime(
      DateTime? selectedDay) async {
    final prefs = await SharedPreferences.getInstance();
    Map<String, dynamic> map = {};
    try {
      var response = await HttpUtil().get(
        "/task/taskByTime",
        data: {"id": prefs.getString("user-id"), "options": selectedDay},
      );
      // 将获取的数据排序
      if (response != null) {
        map = MapSort.mapSort(response['data']);
      }
      return map;
    } catch (e) {
      return map;
    }
  }

  static List<Widget> generateTaskList(
      Map<String, dynamic> map, List<Widget> taskList, DateTime? selectedDay) {
    taskList.clear();
    List<String> keys = map.keys.toList();
    for (var element in keys) {
      if ((map[element] as List).isEmpty) {
        taskList.add(
          AddTaskWidget(
            date: selectedDay,
            time: element,
          ),
        );
      } else {
        taskList.add(TaskUtils.generateTaskList(element, map));
      }
    }
    return taskList;
  }

  static Future<Map<String, dynamic>> getTaskTotalTime() async {
    final prefs = await SharedPreferences.getInstance();
    String? userId = prefs.getString("user-id");
    Map<String, dynamic> totalTimeMap = {};
    DateTime now = DateTime.now();
    try {
      var response = await HttpUtil().get("/task/taskTotalTime",
          data: {"userId": userId, "startTime": now});
      ResponseJsonEntity responseJsonEntity =
          ResponseJsonEntity.fromJson(response);
      if (responseJsonEntity.data != null) {
        totalTimeMap = responseJsonEntity.data;
      }
      return totalTimeMap;
    } catch (e) {
      return totalTimeMap;
    }
  }
}
